package org.csu.chatserver.monitor;

import io.netty.channel.Channel;
import org.csu.chatserver.handlerDispatcher.WebSocketHandlerDispatcher;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

//@Component
@Profile("never")
public class HeartbeatMonitor {

    // 直接访问 WebSocketHandlerDispatcher 的静态 Map
    private final Map<String, Long> lastHeartbeatTimeMap = WebSocketHandlerDispatcher.lastHeartbeatTimeMap;
    private final Map<String, Channel> userChannelMap = WebSocketHandlerDispatcher.userChannelMap;

    // 每10秒检查一次
    @Scheduled(fixedRate = 10000)
    public void checkHeartbeat() {
        long now = System.currentTimeMillis();
        for (Map.Entry<String, Long> entry : lastHeartbeatTimeMap.entrySet()) {
            if (now - entry.getValue() > 60000) { // 超过60秒没心跳
                String userId = entry.getKey();
                Channel channel = userChannelMap.get(userId);
                if (channel != null) {
                    channel.close();
                    System.out.println("[心跳检测] 用户 " + userId + " 超时未响应，断开连接");
                    // 可选：清理 map
                    userChannelMap.remove(userId);
                    lastHeartbeatTimeMap.remove(userId);
                }
            }
        }
    }
}

